package anatex.translate;

import java.util.Date;
import java.util.List;
import java.util.ListIterator;

import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import anatex.domain.Document;
import anatex.domain.Keyword;
import anatex.domain.KeywordDocument;
import anatex.semantics.RelatedCategoriesFinder;
import anatex.semantics.RelatedDocumentsFinder;
import anatex.service.Settings;
import anatex.translate.TranslateTask;
import anatex.translate.TranslatedKeyword;
import org.springframework.dao.EmptyResultDataAccessException;
import com.google.api.translate.Language;
import com.google.api.translate.Translate;

//@Service
public class TranslateService {

	private static Integer timeCounter = 0;
	private static Integer splitCounter = 0;
	private static Long splitTask = 0L;
	
	@Scheduled(fixedRate=60000)
	public void executeTranslation() {
		Settings settings = Settings.getDefaultConfig();
		System.out.print("t");
		if(settings.getTranslationServiceEnabled() == false){
			return;
		}else{
			if(TranslateService.timeCounter<settings.getTranslationTimeInterval()){
				TranslateService.timeCounter++;
				return;
			}else{
				TranslateService.timeCounter = 0;
			}
		}
		
		TranslateTask task = null;
		if(splitCounter > 0){
			try{
			task = TranslateTask.findTranslateTask(TranslateService.splitTask);
			}catch (Exception ex) {
				System.out.println("Split Translate error");
				ex.printStackTrace(System.out);
			}
		} else
		try {
			task = TranslateTask.findTranslateTasksByCurrentStateAndEnabled(TranslateTask.EnumState.NOT_STARTED,
					true).setFirstResult(0).setMaxResults(1).getSingleResult();
		}catch(EmptyResultDataAccessException ex){
			return;
		}catch (Exception ex) {
			System.out.println("TranslateService error");
			ex.printStackTrace(System.out);
		}
		if (task != null){
			task.setCurrentState(TranslateTask.EnumState.WORKING);
			task = task.merge();
			System.out.println("start Translation");
			try {
				//TODO: Google Translate here
				
				if(task.getLength() > 4990){
					//TODO: split
					//TranslateService.splitTask = task.getId();
				}
				
				List<KeywordDocument> words = KeywordDocument.findKeywordDocumentsByDocument(task.getDocument()).getResultList();
				System.out.println("Keywords: " + words.size());
				String[] ktext = new String[words.size()];
				
		    	for(int i=0; i<words.size(); i++){
		    		ktext[i] = words.get(i).getKeyword().getText();
		    	}
				
				//Set the HTTP referrer to testing address (allows more translations).
			    Translate.setHttpReferrer("localhost");
			    String[] translAll;
				translAll = Translate.execute(
							ktext,
							task.getDocument().getCustomLocale().toGoogleLang(),
							task.getLocale().toGoogleLang());				
				
				System.out.println("Translated Keywords: ");
				for(int i=0; i<words.size(); i++){
					System.out.println(ktext[i] + " =?= " + translAll[i]);
					TranslatedKeyword tk = new TranslatedKeyword();
					tk.setGoogleTranslation(translAll[i]);
					tk.setKeyword(words.get(i).getKeyword());
					tk.setLocale(task.getLocale());
					tk.setUserTranslation("");
					tk.persist();	
		    	}		    	
			    
			} catch (Exception ex) {
				System.out.println("Translate error");
				ex.printStackTrace(System.out);
			}
			task.setTranslationTime(new Date());
			task.setCurrentState(TranslateTask.EnumState.FINISHED);
			task = task.merge();
			
			RelatedCategoriesFinder rcf = new RelatedCategoriesFinder();
			RelatedDocumentsFinder rdf = new RelatedDocumentsFinder();
			
			rcf.findAndLog(task.getDocument());
			rdf.findAndLog(task.getDocument());
			
		}else{
			System.out.println("No translation tasks found.");
		}
	 
	}
}

	